package component;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;

import network.HttpServerErrors;
import util.UnstackableToast;
import util.http.HttpPostConnector;
import winapi251.app.fortpolio.R;

/**
 * 회원가입 액티비티
 */
public class JoinActivity extends Activity
{
	private static final String LOG_TAG = "WAFortPolio_component.JoinActivity";

	private EditText editEmail;
	private EditText editPassword;
	private EditText editPasswordConfirm;
	private EditText editName;
	private EditText editDay;
	private EditText editMonth;
	private EditText editYear;

	/**
	 * 회원가입 액티비티가 생성될 때 호출되는 메서드
	 * @param savedInstanceState : 저장되어 있던 인스턴스 상태
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join);

		// 레이아웃에 있는 뷰들을 불러온다.
		editEmail = (EditText) findViewById(R.id.edit_email);
		editPassword = (EditText) findViewById(R.id.edit_password);
		editPasswordConfirm = (EditText) findViewById(R.id.edit_password_confirm);
		editName = (EditText) findViewById(R.id.edit_name);
		editYear = (EditText) findViewById(R.id.edit_year);
		editMonth = (EditText) findViewById(R.id.edit_month);
		editDay = (EditText) findViewById(R.id.edit_day);
	}

	/**
	 * 회원가입 액티비티의 버튼이 눌렸을 때 호출되는 메서드
	 * @param view : 눌린 버튼
	 */
	public void onClick(View view)
	{
		switch (view.getId())
		{
		case R.id.btn_join: // 회원가입 버튼
			final String email = editEmail.getText().toString();
			final String password = editPassword.getText().toString();
			final String passwordConfirm = editPasswordConfirm.getText().toString();
			final String name = editName.getText().toString();
			final String year = editYear.getText().toString();
			final String month = editMonth.getText().toString();
			final String day = editDay.getText().toString();

			try
			{
				if (email.equals(""))
					throw new Exception("이메일");

				else if (password.equals(""))
					throw new Exception("비밀번호");

				else if (!passwordConfirm.equals(password))
				{
					UnstackableToast.show("비밀번호를 확인해주세요.", Toast.LENGTH_LONG);
					return;
				}

				else if (name.equals(""))
					throw new Exception("이름");

				else if (year.equals(""))
					throw new Exception("생년월일");

				else if (month.equals(""))
					throw new Exception("생년월일");

				else if (day.equals(""))
					throw new Exception("생년월일");
			}
			catch (Exception exception)
			{
				UnstackableToast.show(exception.getMessage() + "을 입력해주세요.", Toast.LENGTH_LONG);
				return;
			}

			new Thread()
			{
				@Override
				public void run()
				{
					try
					{
						// 서버에 회원가입을 요청한다.
						HttpPostConnector connector = new HttpPostConnector("http://contest.iwop.net/2013/fortpolio/mobile_join.php");
						String html = connector.request(
								"joinEmail", email,
								"joinPwd", password,
								"joinPwd_Check", passwordConfirm,
								"joinName", name,
								"joinBirthday", (year + "-" + month + "-" + day));
						Log.v(LOG_TAG, html);

						// 서버와 통신하는 중 발생한 오류를 처리한다.
						int errorCode = Integer.parseInt(html);
						switch (errorCode)
						{
						case HttpServerErrors.NO_ERROR:
							// 로그인 페이지로 이동한다.
							finish();
							startActivity(new Intent(JoinActivity.this, LoginActivity.class));
							break;

						case HttpServerErrors.FORBIDDEN:
							throw new Exception("잘못된 접근입니다.");

						case HttpServerErrors.UNCORRECT_CONFIRM:
							throw new Exception("비밀번호를 확인해주세요.");

						case HttpServerErrors.DUPLICATED_ID:
							throw new Exception("이미 존재하는 아이디입니다.");
						}
					}

					catch (IOException e)
					{
						Log.v(LOG_TAG, "네트워크 IOException 발생!");
					}

					// 서버와 통신하던 중 발생한 예외처리 코드
					catch (Exception execption)
					{
						UnstackableToast.show(execption.getMessage(), Toast.LENGTH_LONG);
					}
				}
			}.start();
			break;
		}
	}
}